package com.yykj.drup.server.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yykj.drup.server.constant.SysConstant;
import com.yykj.drup.server.model.OrderInfo;
import com.yykj.drup.server.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * @Author zeng
 * @Date 2022/3/24
 */
@Component
@Slf4j
public class ScheduledConfig {

    private Logger logger = LoggerFactory.getLogger(ScheduledConfig.class);

    @Autowired
    private OrderInfoService orderInfoService;

    //
    ///**
    // * 每分钟执行：将超时未支付的订单，状态改为 取消
    // */
    //@Scheduled(cron = "59 * * * * ?")
    //public void cancelOrderStatus() {
    //    String timeout = redisService.get("orderPayTimeout");
    //    //logger.info("获取订单超时时间值 :" + timeout);
    //    LocalDateTime localDateTime = LocalDateTime.now();
    //    if (StrUtil.isEmpty(timeout)){
    //        timeout = SysConstant.timeoutDef;
    //    }
    //    logger.info("将超时未支付的订单状态改为:取消");
    //    orderService.cancelOrderStatus(localDateTime.minusMinutes(Integer.parseInt(timeout)));
    //}

    /**
     * 每天凌晨1点执行：将物流已签收的订单自动执行用户确认收货
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void cancelOrderInfoStatus() {
        /**
         * 获取物流签收7天，仍未确认收货的
         */
        LocalDate localDate = LocalDate.now().minusDays(SysConstant.checkTimeoutDef);
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper
                //设置查询条件：物流状态已签收
                .eq(OrderInfo::getOrderComCheck,1)
                //设置查询条件：确认收货状态未收货
                .eq(OrderInfo::getOrderStoreCheck,0)
                //设置查询条件：物流签收时间超过指定天数
                .le(OrderInfo::getOrderComCheckTime,localDate);
        List<OrderInfo> infoList = orderInfoService.list(wrapper);
        logger.info("获取物流签收7天，仍未确认收货的订单{}",infoList);
        infoList.stream().forEach(info->{
            Boolean check = orderInfoService.setOrderInfoCheck(info.getId());
            logger.info("药店订单号{}，执行确认收货{}",info.getId(),check);
            if (check){
                //更新系统总订单状态
                logger.info("更新系统订单{},状态完成",info.getOrderSysNum());
                orderInfoService.setOrderStatusOK(info.getOrderSysNum());
            }
        });
    }
}
